package cn.itcast.consumer.web;

import cn.itcast.consumer.client.UserClient;
import cn.itcast.consumer.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private UserClient userClient;

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id){
        return userClient.queryById(id);
    }


   /* @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "queryByIdFallback", commandProperties = {
            //@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),// 测试10次请求
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000")// 休眠时间10s
    })
    @GetMapping("{id}")
    public String queryById(@PathVariable("id") Long id){
        // 人为控制请求的成功和失败
        if(id == 1){
            // 人为失败
            throw new RuntimeException("我是故意的！");
        }

        // 请求的url地址，我们用service-id代替`host:port`
        // Ribbon会自己根据serviceId，拉取服务列表，利用负载均衡，获取服务地址
        String url = "http://user-service/user/" + id;
        // 远程调用
        return restTemplate.getForObject(url, String.class);
    }

    // 应急（兜底）方案。
    public String queryByIdFallback(Long id){
        return "别挤了，服务器都快炸了！";
    }*/

    // 负载均衡的客户端，帮助我们去eureka拉取服务列表
    /*@Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id){
        // 拉取服务实例列表
        List<ServiceInstance> list = discoveryClient.getInstances("user-service");
        // 从服务实例列表中，利用负载均衡算法，获取其中一个实例。比如：随机负载均衡
        int index = new Random().nextInt(list.size());
        ServiceInstance instance = list.get(index);
        // url路径
        String host = instance.getHost();
        int port = instance.getPort();
        String url = String.format("http://%s:%d/user/%d", host, port, id);
        // 远程调用
        return restTemplate.getForObject(url, User.class);
    }*/
}
